using Gtk;
using Pango;
using Gdk;

int main (string[] args) {
	var dir1 = GLib.Path.get_dirname(args[0]);
	var path1 = GLib.Path.build_filename(dir1,"chat.ui");
	//stdout.printf("%s\n%s\n",args[0],path1);
    Gtk.init (ref args);
	var app1 = new MyApp();
	var ret = app1.show(path1);
	if (ret) {
		Gtk.main();
	}
    return 0;
}

class MyApp:GLib.Object{
	public Gtk.Builder builder1;
	public int step = 1;
	
	public bool show(string ui){
		this.builder1 = new Gtk.Builder.from_file(ui);
		var win1 = (Gtk.Window)this.builder1.get_object("win1");
		var listMsg = (Gtk.TreeView)this.builder1.get_object("listMsg");
		listMsg.set_size_request(620,410);
		win1.set_default_size (640,480);
		win1.show_all();
		
		this.setup_msgs();
		//this.append_msgs();
		//this.setup_users();
		//this.append_users();
		this.append_msg("sys","输入IRC服务器（默认：'chat.freenode.net:6667'）");
		
		ChatInit(0); // 1 => verbose
		Thread<int> thread;
		if (Thread.supported()==false){
			stdout.printf("runtime not support Thread\nExit\n");
			return false;
		} else {
			try{
				thread = new Thread<int>.try ("irc1", this.loop_msgs);
			} catch(Error e) {
				stdout.printf ("Error: %s\n", e.message);
				return false;
			}
			//thread = new Thread<int>("irc1", this.loop_msgs);
		}
		
		win1.destroy.connect(()=>{
			if(this.step>4){
				Quit();
				stdout.printf("Disconnect IRC.\n");
				thread.join();
			}
			Gtk.main_quit();
		});
		
		var entry1 = (Gtk.Entry)this.builder1.get_object("entryMsg");
		entry1.activate.connect( (self)=>{
			var s = self.get_text();
			self.set_text("");
			switch(GetStep()){
			case 1:
				this.step = SetIRCServer(s);
				this.append_msg("sys",GetHead(0));
				this.append_msg("sys","输入用户名（默认值：随机名称）");
				break;
			case 2:
				this.step = SetNick(s);
				this.append_msg("sys",GetHead(0));
				this.append_msg("sys","输入房间名（默认值：随机名称）");
				break;
			case 3:
				string room;
				this.step = SetRoom(s,out room);
				//this.append_user( room );
				var target = (Gtk.Label)this.builder1.get_object("labelTarget");
				target.set_text(room);
				this.append_msg("sys",GetHead(0));
				this.append_msg("sys","输入密钥（长度必须大于0）");
				self.set_visibility(false);
				break;
			case 4:
				this.step = SetKey(s);
				var h = GetHead(0);
				var top = (Gtk.Label)this.builder1.get_object("topMsg");
				top.set_text(h);
				this.append_msg("sys","连接中...");
				self.set_visibility(true);
				break;
			case 6:
				if(s==""){
					break;
				}
				var target = (Gtk.Label)this.builder1.get_object("labelTarget");
				var chan1 = target.get_text();
				Say(chan1, s);
				this.append_msg("你",s);
				break;
			}
		});
		return true;
	}
	
	public int loop_msgs(){
		int ret;
		while(true){
			string from,msg;
			ret = GetMsg(out from, out msg);
			//stdout.printf("%d: %s %s\n",ret,from,msg);
			if (ret==1){
				GLib.Idle.add( ()=>{
					this.append_msg(from,msg);
					return false;
				});
				
				if((msg=="you join") && (from=="sys")){
					GLib.Idle.add( ()=>{
						var h = GetHead(1);
						var top = (Gtk.Label)this.builder1.get_object("topMsg");
						top.set_text(h);
						this.append_msg("sys",h);
						return false;
					});
				}
			}else{
				break;
			}
		}
		stdout.printf("Exit Message Loop.\n");
		return ret;
	}
	
//	public void append_msgs(){
//		var listMsg = (Gtk.TreeView)this.builder1.get_object("listMsg");
//		Gtk.ListStore store1 = (Gtk.ListStore)listMsg.get_model();
//		Gtk.TreeIter iter;
//		store1.append(out iter);
//		store1.set (iter, 0, "Band", 1, """hello 4. 这才农历九月初，大秋天的，深圳的天气就已经降温了。更搞笑的是，朋友圈、群里都在转发下面这张图片，相信大部分人已经看过了吧。 这是哪家公司的？""");
//		store1.append(out iter);
//		store1.set (iter, 0, "top", 1, "hello 5");
//		store1.append(out iter);
//		store1.set (iter, 0, "Band", 1, "hello 6");
//	}
	public void append_msg(string sender,string msg){
		var listMsg = (Gtk.TreeView)this.builder1.get_object("listMsg");
		Gtk.ListStore store1 = (Gtk.ListStore)listMsg.get_model();
		var model1 = listMsg.get_model();
		Gtk.TreeIter iter;
		store1.append(out iter);
		store1.set(iter, 0, sender, 1, msg);
		var path1 = model1.get_path(iter);
		listMsg.scroll_to_cell(path1,null,false,0,0);
		//listMsg.show_all();
	}
	public void setup_msgs(){
		var listMsg = (Gtk.TreeView)this.builder1.get_object("listMsg");
		listMsg.enable_grid_lines = Gtk.BOTH;
		var store1 = new Gtk.ListStore (2, typeof (string), typeof (string));
		Gtk.CellRendererText cmsg = (Gtk.CellRendererText)this.builder1.get_object("msg-renderer");
		Gtk.CellRendererText csender = (Gtk.CellRendererText)this.builder1.get_object("sender-renderer");
		cmsg.wrap_mode = Pango.CHAR;
		cmsg.wrap_width = 450;
		csender.yalign = 0; 
		listMsg.set_model(store1);
		listMsg.row_activated.connect( (tree,path,col)=>{
			//stdout.printf("%s\n",path.to_string());
			Gtk.TreeIter iter;
			var model = tree.get_model();
			model.get_iter(out iter,path);
			GLib.Value v1= Value(typeof (string));;
			model.get_value(iter,1,out v1);
			//stdout.printf("%s\n",v1.get_string());
			var entry1 = (Gtk.Entry)this.builder1.get_object("entryMsg");
			entry1.set_text(v1.get_string());
		});
	}
//	public void append_users(){
//		var listUser = (Gtk.ListBox)this.builder1.get_object("listUser");
//		string[] users = {"loly","tom","fisher"};
//		Gdk.Color c;
//		Gdk.Color.parse("#0099ff",out c);
//		foreach (var u in users){
//			var item1 = new Gtk.Label(u);
//			item1.modify_bg(Gtk.NORMAL,c);
//			listUser.add(item1);
//		}
//		listUser.show_all();
//	}
//	public void append_user(string u){
//		var listUser = (Gtk.ListBox)this.builder1.get_object("listUser");
//		Gdk.Color c;
//		Gdk.Color.parse("#0099ff",out c);
//		var item1 = new Gtk.Label(u);
//		item1.modify_bg(Gtk.NORMAL,c);
//		listUser.add(item1);
//		listUser.show_all();
//	}
//	public void setup_users(){
//		var listUser = (Gtk.ListBox)this.builder1.get_object("listUser");
//		var ch1 = "#channel";
//		var item1 = new Gtk.Label(ch1);
//		Gdk.Color c;
//		Gdk.Color.parse("#0099ff",out c);
//		item1.modify_bg(Gtk.NORMAL,c);
//		listUser.prepend(new Gtk.Label("可选的目标"));
//		listUser.add(item1);
//		listUser.show_all();
//		var target = (Gtk.Label)this.builder1.get_object("lableTarget");
//		target.set_text( ch1 );
//		listUser.row_selected.connect( (list,row)=>{
//			var list1 = list.get_selected_row ().get_children();
//			var label = (Gtk.Label)list1.nth_data(0);
//			var text1 = label.get_text();
//			target.set_text(text1);
//		});
//	}
}
